package com.qf.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.constans.SystemParameter;
import com.qf.feign.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

/**
 * 自定义规则，确定用户想要请求的服务和url
 */

@Component
public class RoutingFilter extends ZuulFilter {

    @Resource
    private RedisService redisService;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 100;
    }

    @Override
    public boolean shouldFilter() {
        return RequestContext.getCurrentContext().sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {
        //自定义规则，指定不同的method参数访问不同的服务
        //在redis中通过hash存放每一种method参数所代表的服务和路径

        //获得request对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String method = request.getParameter("method");

        //通过redis获得用户请求的服务和路径
//        Map<Object, Object> map = redisService.hgetAll(SystemParameter.REDISAPIPRE+":"+method);
        Map<Object, Object> apiinfoMap = SystemParameter.apiinfoMap;
        Map map = (Map) apiinfoMap.get(SystemParameter.REDISAPIPRE + ":" + method);
        if (map!=null && map.size()>=2){

            System.out.println("需要用到的服务为："+map);
            //设置需要请求的服务
            currentContext.put(FilterConstants.SERVICE_ID_KEY,map.get("sessionId"));
            //告诉zuul需要请求的服务地址
            //对于restFul的请求需要进行手动封装参数
            String url = (String) map.get("url");
            System.out.println("替换前的URL："+url);
            Enumeration<String> parameterNames = request.getParameterNames();//获取请求中的全部参数名
            while (parameterNames.hasMoreElements()){
                String name = parameterNames.nextElement();
                url = url.replaceAll("\\{" + name + "\\}", request.getParameter(name));
            }
            System.out.println("替换后的URL："+url);


            currentContext.put(FilterConstants.REQUEST_URI_KEY,url);

        }else {
            //从redis中接收的参数不完整
            currentContext.getResponse().setContentType("text/html;charset=utf-8");
            currentContext.setResponseBody("method的参数不可用！");
            currentContext.setSendZuulResponse(false);
        }


        return null;
    }
}
